import {decrypt, encrypt} from 'crypto-js/aes';
import UTF8, {parse} from 'crypto-js/enc-utf8';
import pkcs7 from 'crypto-js/pad-pkcs7';
import ECB from 'crypto-js/mode-ecb';
import md5 from 'crypto-js/md5';
import {LocationQueryValue} from "vue-router";
import CryptoJS from "crypto-js";

export interface EncryptionParams {
  key: string;
  iv: string;
}

export class AesEncryption {
  private key;
  private iv;

  constructor(opt: Partial<EncryptionParams> = {}) {
    const {key, iv} = opt;
    if (key) {
      this.key = parse(key);
    }
    if (iv) {
      this.iv = parse(iv);
    }
  }

  get getOptions() {
    return {
      mode: ECB,
      padding: pkcs7,
      iv: this.iv,
    };
  }

  encryptByAES(cipherText: string) {
    return encrypt(cipherText, this.key, this.getOptions).toString();
  }

  decryptByAES(cipherText: string) {
    return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
  }
}

export function encryptByBase64(cipherText: string) {
  return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(cipherText));
}

export function decodeByBase64(cipherText: string) {
  return CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(cipherText)).toString();
}

export function encryptByMd5(password: string) {
  return md5(password).toString();
}
export function encryptByMd5Pass(password: string) {
  return md5(password).toString().toUpperCase();
}

export function encodeAes(str: string | undefined) {
  if (!str) {
    return ''
  }
  const encryption = new AesEncryption({
    key: import.meta.env.VITE_AES_KEY as any,
  });
  return encryption.encryptByAES(str);
}

export function decodeAes(str: string | null | LocationQueryValue[]) {
  if (!str) {
    return ''
  }
  const encryption = new AesEncryption({
    key: import.meta.env.VITE_AES_KEY as any,
  });
  return encryption.decryptByAES(str);
}
